package deng.service.filepoller;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.log4j.Logger;

import deng.service.Service;
import deng.service.util.Utils;

/**
 * A service that provide a timer to poll a directory and pass all files to
 * a {@link FileHandler} for processing.
 *
 * @author Zemian Deng
 */
public class FilePollerService implements Service {
	
	private static Logger logger = Logger.getLogger(FilePollerService.class);
	private File pollDirectory = new File(".");
	private long pollInterval = 5000;
	private long pollInitDelay = 1000;
	private FileHandler fileHandler = new SimpleFileHandler();
	private Timer timer;
	
	private class FilePollerTimerTask extends TimerTask {

		@Override
		public void run() {
			logger.debug("Polling dir: " + pollDirectory);
			File[] files = pollDirectory.listFiles();
			if (files != null && files.length > 0)
				FilePollerService.this.processFile(files);
		}
		
	}
	
	public void setFileHandler(FileHandler fileHandler) {
		this.fileHandler = fileHandler;
	}
	
	public void setPollDirectory(File pollDirectory) {
		this.pollDirectory = pollDirectory;
	}
	
	public void setPollInterval(long pollInterval) {
		this.pollInterval = pollInterval;
	}
	
	public void setPollInitDelay(long pollInitDelay) {
		this.pollInitDelay = pollInitDelay;
	}
	
	@Override
	public String toString() {
		return getClass().getSimpleName() + "[" +
				"pollInitDelay=" + pollInitDelay + 
				", pollDirectory=" + pollDirectory + 
				", pollInterval=" + pollInterval + "]";
	}

	@Override
	public void start() {
		if (timer != null) 
			throw new RuntimeException("Timer has already started.");

		logger.debug("Starting " + this);
		FilePollerTimerTask timerTask = new FilePollerTimerTask();
		timer = new Timer(FilePollerService.class.getName());
		timer.schedule(timerTask, pollInitDelay, pollInterval);
	}

	@Override
	public void stop() {
		if (timer == null) 
			throw new RuntimeException("Timer has not started.");
		
		logger.debug("Stopping " + this);
		timer.cancel();
		timer = null;
	}
	
	protected void processFile(File[] files) {
		logger.debug("Processing " + Utils.arrayToString("Files", files));
		fileHandler.process(files);
	}
}
